import React from 'react';
import { Form, Field, Input, Button, Message, Balloon } from '@teamix/ui';
import { ButtonIcon } from '@alife/devops-ui';
import ListEmpty from 'components/PersonalSettings/components/ListEmpty';
import ListLoading from 'components/PersonalSettings/components/ListLoading';
import SshItem from './sshItem';
import exceed from 'utils/apimap';
import './index.scss';
import intl from 'components/PersonalSettings/components/locale';

const FormItem = Form.Item;
const prefix = 'ssh-secret';

const gpgDoc = 'https://help.aliyun.com/document_detail/206892.html';

class GpgKey extends React.Component {
  constructor(props) {
    super(props);
    this.field = new Field(this);
    this.state = {
      submitting: false,
      keys: [],
      total: 0,
      isLoadingTable: true,
    };
  }

  componentDidMount() {
    this.getKeys();
  }

  onKeyInputChange = (value) => {
    const key = value.trim();
    const strArr = key.split(' ');
    const title = strArr[strArr.length - 1];

    this.field.setValue('key', value);
    if (strArr.length > 1) {
      this.field.setValue('title', title);
    }
  };

  handleSubmit = () => {
    this.field.validate((errors) => {
      if (!errors) {
        this.setState({ submitting: true });
        const formData = this.field.getValues();
        this.postKey(formData, (isFail) => {
          if (!isFail) {
            this.field.reset();
          }
          this.setState({ submitting: false });
        });
      }
    });
  };

  getKeys = () => {
    exceed
      .forceFetch({
        api: 'gpg.list',
        data: {
          page: 1,
          per_page: 100,
        },
      })
      .then((result) => {
        const { list } = result;
        if (list === null) {
          this.setState({
            keys: [],
            total: 0,
            isLoadingTable: false,
          });
        } else {
          this.setState({
            keys: list,
            total: list.length,
            isLoadingTable: false,
          });
        }
      })
      .catch(() => {
        this.setState({
          isLoadingTable: false,
        });
      });
  };

  postKey = (formData, cb) => {
    exceed
      .fetch({
        api: 'gpg.post',
        data: {
          ...formData,
        },
      })
      .then((result) => {
        if (result && result.id) {
          setTimeout(() => {
            Message.success({
              title: '添加成功',
            });
          }, 500);
          this.getKeys();
        } else if (result && result.message) {
          Message.error({
            title: result.message,
          });
        }

        cb && cb();
      })
      .catch(() => {
        // 接口报错也要回调，以让按钮取消loading状态
        cb && cb('isFail');
      });
  };

  checkKey = (rule, value, callback) => {
    const startStr = '-----BEGIN PGP PUBLIC KEY BLOCK-----';
    const endStr = '-----END PGP PUBLIC KEY BLOCK-----';
    if (value.trim().indexOf(startStr) !== 0 || value.trim().slice(-endStr.length) !== endStr) {
      return callback(
        intl.auto(
          '无效的 PGP 公钥，必须包含头 “-----BEGIN PGP PUBLIC KEY BLOCK-----”  及 尾 “-----END PGP PUBLIC KEY BLOCK-----”',
          'Invalid PGP public key, must include the header "-----BEGIN PGP PUBLIC KEY BLOCK-----" and the end "-----END PGP PUBLIC KEY BLOCK-----"',
        ),
      );
    } else {
      return callback();
    }
  };

  render() {
    const { init } = this.field;
    const { keys, total, isLoadingTable } = this.state;
    return (
      <div style={{ marginLeft: 20, marginRight: 20, height: 600 }}>
        <div className={`${prefix}-title`}>
          {intl.get('add_gpg_key')}
          <Balloon
            type="normal"
            closable={false}
            trigger={
              <ButtonIcon
                type="secondary"
                name="question-line"
                style={{ marginLeft: 4, display: 'inline-block' }}
              />
            }
            align="t"
          >
            {intl.get('authenticity_signature_verification_of_submission')}{' '}
            <a target="_blank" href={gpgDoc} rel="noreferrer">
              {intl.get('understand_more')}
            </a>
          </Balloon>
        </div>
        <Form field={this.field}>
          <FormItem label={intl.get('key')} required>
            <div className="add-key-tip">
              {intl.auto(
                '在你添加一个 GPG 公钥 前，你需要 ',
                'Before you add a GPG key, you need ',
              )}
              <a href={gpgDoc} target="_blank" rel="noopener noreferrer">
                {intl.get('generate_ssh_key')}
              </a>
            </div>
            <Input.TextArea
              {...init('key', {
                rules: [
                  { required: true, message: intl.get('item_necessary'), trigger: ['onKeyUp'] },
                  { validator: this.checkKey, trigger: ['onKeyUp'] },
                ],
              })}
              placeholder={intl.auto(
                '请粘贴你的 GPG 公钥，包含以“-----BEGIN PGP PUBLIC KEY BLOCK-----”开头, \n以“-----END PGP PUBLIC KEY BLOCK-----”结尾的完整内容',
                'Please paste your GPG public key, including beginning with "-----BEGIN PGP PUBLIC KEY BLOCK-----" and \nbeginning with "-----END PGP PUBLIC KEY BLOCK- ----" the complete content at the end',
              )}
              onChange={this.onKeyInputChange}
            />
          </FormItem>
          {/* <FormItem label={intl.get('item_title')} required>
            <Input
              {...init('title', {
                rules: [{ required: true, message: intl.get('item_necessary') }],
              })}
              placeholder="请输入公钥标题"
            />
          </FormItem> */}
          <FormItem label="">
            <Button type="primary" onClick={this.handleSubmit} loading={this.state.submitting}>
              {intl.get('item_add')}
            </Button>
          </FormItem>
        </Form>
        <div className={`${prefix}-divide`} />
        {!isLoadingTable ? (
          <div style={{ marginTop: 30, marginBottom: 30 }}>
            <div className={`${prefix}-title`}>{`${intl.get('has_keys')} · ${total}`}</div>
            {keys && keys.length > 0 ? (
              <div>
                {keys.map((item) => (
                  <SshItem
                    key={item.id}
                    dataSource={item}
                    getKeys={this.getKeys}
                    uiless_config={window.UILessConfig}
                  />
                ))}
              </div>
            ) : (
              <ListEmpty content={intl.get('no_data')} imgType="data" />
            )}
          </div>
        ) : (
          <ListLoading />
        )}
      </div>
    );
  }
}

export default GpgKey;
